import 'dart:async';
import 'dart:collection';

import 'package:flutter/cupertino.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:smart_translator/app/storage/StorageManager.dart';

import '../../../beans/buser_model.dart';
import '../../../const/AppConst.dart';
import '../../../const/AppConstUrl.dart';
import '../../../db/DbDAOHelper.dart';
import '../../../event/DataCallBack.dart';
import '../../../nets/NetWorkManager.dart';
import '../../../routes/app_pages.dart';
import '../../../utils/CommonUtil.dart';
import '../../../utils/tips.dart';

class LoginController extends GetxController {
  var suffixIconsVisible = false.obs;
  var pwVisible = false.obs;

  var accountController = TextEditingController().obs;
  var passwordCodeController = TextEditingController().obs;

  var isSubmitBtnEnable = false.obs;
  var checkBoxChecked = false.obs;

  var  accountFocusNode = FocusNode().obs;
  var  pwFocusNode = FocusNode().obs;

  var scrollController = ScrollController().obs;
  // late StreamSubscription<bool> keyboardSubscription;


  @override
  void onInit() {
    super.onInit();
    // Subscribe
    /*keyboardSubscription = KeyboardVisibilityController().onChange.listen((bool visible) {
      print('Keyboard visibility update. Is visible: $visible');
      if(visible) {
        Future.delayed(Duration(milliseconds: 500), () {
          scrollToBottom();
        });



      }
    });*/
  }


  void scrollToBottom() {
    scrollController.value.jumpTo(
      170.h
    );
    /*scrollController.value.animateTo(
      170.h,
      duration: const Duration(seconds: 2),
      curve: Curves.easeOut,
    );*/
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.value.dispose();
    // keyboardSubscription.cancel();

  }

  void setSuffixIconsVisible(bool visible) {
    suffixIconsVisible.value = visible;
  }

  void onTextFieldChange(v,type) {
    if(type =='name'){
      if (v != null && v != '') {
        suffixIconsVisible.value = true;
      } else {
        suffixIconsVisible.value = false;
      }
    }


    //检查btn提交按钮是否可以点击.
    if(simpleChecking()) {
      isSubmitBtnEnable.value = true;
    } else {
      isSubmitBtnEnable.value = false;
    }
  }

  bool simpleChecking() {
    return accountController.value.text != '' && passwordCodeController.value.text != '';
  }

  void onCheckBoxChange() {
    if(simpleChecking()) {
      isSubmitBtnEnable.value = true;
    } else {
      isSubmitBtnEnable.value = false;
    }
  }

  void onTapUserAgreementTask() {
    accountFocusNode.value.unfocus();
    pwFocusNode.value.unfocus();

    Map<String, String> param = HashMap();
    param["title"] = "用户协议";
    param["url"] = AppConstUrl.LOGIN_USER_AGREEMENT_URL;
    Get.toNamed(Routes.WEBVIEW, parameters: param);
  }

  void onTapPrivacyPolicyTask() {
    accountFocusNode.value.unfocus();
    pwFocusNode.value.unfocus();

    Map<String, String> param = HashMap();
    param["title"] = "隐私政策";
    param["url"] = AppConstUrl.LOGIN_PRIVACY_POLICY_URL;
    Get.toNamed(Routes.WEBVIEW, parameters: param);
  }

  void register() {
    Get.toNamed(Routes.REGIST);
    clearData();
  }

  void forgetPasswd() {
    Get.toNamed(Routes.FORGOT_PASSWD);
    clearData();
  }

  void login() {
    accountFocusNode.value.unfocus();
    pwFocusNode.value.unfocus();

    NetWorkManager.getInstance().requestBussiness(NetWorkManager.M_Login, {
      'username': accountController.value.text,
      'password': passwordCodeController.value.text

    }, NetWorkManager.methodPOST, DataCallBack(
        businessCallBack: (v) {
          StorageManager.getStorage().write(AppConst.LOGIN_TOKEN, v['token']);
          StorageManager.getStorage().write(AppConst.LOGIN_USER, v['userInfo']);

          Buser buser = Buser.fromJson(v['userInfo']);
          buser.token = v['token'];

          DbDAOHelper().updateLoginUser(buser);

          if(!CommonUtil.hasEnteredAPPBefore()) {
            StorageManager.getStorage().write(AppConst.FIRST_LOGIN, true);
            // managers
            Get.toNamed(Routes.CHOOSE_DEVICE);
          } else {
            Get.toNamed(Routes.HOME);
          }


        },
        errorCallBack: (v) {
          Tips.showToast(v);
        }

    ),showLoading: true);


  }
  void clearData(){
    accountController.value.text = '';
    suffixIconsVisible.value = false;
    pwVisible.value = false;
    passwordCodeController.value.text ='' ;
    checkBoxChecked.value = false;
    accountFocusNode.value.unfocus();
    pwFocusNode.value.unfocus();

  }

  // 忘记密码自动跳转到登录显示默认新名字
  void updateName(name){
    accountController.value.text = name;
  }

}
